<template>
  <div>
    <div class="search-by-image-result-page">
      <div class="layout-right">
        <!-- <div class="stick-box" style="top:84px;"> -->
          <div class="tit">传图搜游戏 <div class="mini-tip" v-if="false">拖动方框选择搜索区域</div></div>
          <div class="basic-img-box-wrap" :style="'max-height:'+maxHeight+'px'">
            <div class="img-box-wra">
              <div class="basic-img-box">
                <div class="op-row">
                  拖拽边角调整范围
                  <a @click="isAgain = true">重新搜索</a>
                  <!-- <a class="xs-fav"></a> -->
                </div>
                  <div class="img-box">
                    <img loading="lazy" :src="imgBase64" alt="" ref="gimage">
                  </div>
                </div>
              </div>
          </div>
          <!-- <div class="tj-tag-box">
            <div class="tit">
              可能寻找的标签
            </div>
            <div class="tags">
              <a href="/searchs?keyword=暂停" target="_blank">暂停</a>
              <a href="/searchs?keyword=招募" target="_blank">招募</a>
              <a href="/searchs?keyword=排行榜" target="_blank">排行榜</a>
              <a href="/searchs?keyword=木头" target="_blank">木头</a>
              <a href="/searchs?keyword=纸张" target="_blank">纸张</a>
              <a href="/searchs?keyword=暂停" target="_blank">暂停</a>
              <a href="/searchs?keyword=招募" target="_blank">招募</a>
              <a href="/searchs?keyword=排行榜" target="_blank">排行榜</a>
              <a href="/searchs?keyword=木头" target="_blank">木头</a>
              <a href="/searchs?keyword=纸张" target="_blank">纸张</a>
            </div>
          </div> -->
        <!-- </div> -->
      </div>
      <div class="layout-left">
        <div class="top-row">
          <div class="title">
            AI智能推荐
          </div>
          <div class="label-filter" v-if="params.similar">
            <span class="tit">版式</span>
            <div class="plat-items">
              <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                          <i class="sm-tip" slot-content>横屏</i>
              <span slot="reference" class="pitem h-screen" :class="{active:ori=='横屏'}" @click="chooseOri('横屏')"></span>
              </el-popover>
              <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                          <i class="sm-tip" slot-content>竖屏</i>
                <span slot="reference" class="pitem s-screen" :class="{active:ori=='竖屏'}" @click="chooseOri('竖屏')"></span>
              </el-popover>
            </div>
          </div>
        </div>
        <ul class="mk-rd-datas">
          <WaterfallFlowImgList @xssearch="onXsSearch" id="1" :list="list" :columns="5"  :defaultw="428"/>
          <div class="no-more-text" v-if="!hasMore&&!isloading&&list.length>0">没有更多了</div>
          <div class="pro-bot-loading" v-if="isloading">
              <i class="el-icon-loading"></i>
          </div>
        </ul>
      </div>

    </div>
    
    <UnLoginMask/>

    <div class="bs-layout-fun-mask" @click="isAgain=false" v-if="isAgain"></div>
      <div class="bs-layout-rst-fun" id="up_box" v-show="isAgain" @drop="onDrop" @dragover="onOndragover" @dragenter="onOndragEnter" @dragleave="onOndragLeave" @paste="onPaste">
        <div class="title"><a class="close-be-simliar" @click="isAgain = false"></a></div>
        <div class="small-tip">上传图片查找相似设计，智能识图越搜越准！</div>
        <div class="upload-area-wrap" @paste="onPaste">
          <el-upload class="upload-btn" action="" accept=".jpg,.png,.gif" :show-file-list="false"
            :http-request="pictureBefore"></el-upload>
          <span class="fun-text">拖放图片至此 或 Ctrl+v 粘贴</span>
        </div>
      </div>
  </div>
</template>


<script>
import UnLoginMask from '@/components/UnLoginMask'
import Cropper from "cropperjs";
import * as imageConversion from 'image-conversion'
import SparkMD5 from 'spark-md5'
import WaterfallFlowImgList from '@/components/WaterfallFlowImgList'
import api from '@/api/api'
export default {
  data() {
    return {
      isloading:true,
      curId:'',
      ori:'',
      params:{
        pageSize:50,
        last:''
      },
      maxHeight:0,
      isDrag: false,
      stickyTop: 0,
      imgBase64: '',
      newBase64: '',
      isAgain: false,
      vurl: '',
      hash: '',
      hasMore: true,
      scrollLoaded: false,
      nomore: false,
      sign: '',
      total: 0,
      pageNum: 1,
      pageSize: 40,
      list: []
    }
  },
  components: {WaterfallFlowImgList,UnLoginMask
  },
  watch: {
    '$route': function () {
      this.vurl = this.$route.query.surl;
      this.hash = this.$route.query.sign;
      this.pageNum = 1;
      this.hasMore = true;
      this.nomore = false;
      this.scrollLoaded = false;
      this.list = [];
      this.queryList();
    }
  },
  destroyed() {
    window.removeEventListener('scroll',this.docScroll);
    window.removeEventListener('resize', this.initStickT);
  },
  mounted() {
    $('#app').removeClass('is-game').removeClass('is-scroll');
    if(this.$route.query.similar){
      this.params.similar=this.$route.query.similar;
    }
    this.getMaxHeight();
    this.vurl = this.$route.query.surl;
    this.hash = this.$route.query.sign;

    this.imgBase64 = localStorage.getItem('tmp_im_b64');
    this.queryList();

    let that = this;

    this.$nextTick(() => {
      that.initStickT();
      that.onSImgLoad();
    })

    document.addEventListener('paste', this.onPaste);
    window.addEventListener('scroll',this.docScroll)
    window.addEventListener('resize', this.initStickT)

    let upEl = document.getElementById('up_box');
    upEl.addEventListener('drop', this.onDrop, false);
    upEl.addEventListener('dragover', this.onOndragover, false);
    upEl.addEventListener('dragenter', this.onOndragEnter, false);
    upEl.addEventListener('dragleave', this.onOndragLeave, false);
  },
  methods: {
    docScroll(){
      let that=this;
      let jHeight = document.documentElement.scrollHeight - document.documentElement.scrollTop - document.documentElement.clientHeight;

      if (that.scrollLoaded == false) return;

      if (jHeight <= 200 && that.hasMore) {
        if(!localStorage.getItem('token')){
          that.$parent.noLoginIsTak=false;
          that.$parent.showLoginView=true;
          that.isloading=false;
          window.removeEventListener('scroll',that.docScroll);
          return;
        }
        that.scrollLoaded = false;
        that.handleLoadingMore();
      }
    },
    chooseOri(_ori){
      this.ori=!!this.ori&&this.ori==_ori?'':_ori;
      this.params.orientation=this.ori;
      this.params.last='';
      this.list=[];
      this.hasMore=true;
      this.scrollLoaded=true;
      this.queryList();
    },
    getMaxHeight(){
      // this.maxHeight=document.body.clientHeight-105-32-19-51-$('.tj-tag-box').height()-40;
      this.maxHeight=document.body.clientHeight-105-32-19;
    },
    onOndragLeave(e) {
      this.isDrag = false;
      e.preventDefault();
    },
    onOndragEnter(e) {
      // this.isDrag=true;
      e.preventDefault();
    },
    onOndragover(e) {
      this.isDrag = true;
      e.preventDefault()
    },
    async onDrop(e) {
      // this.isDrag=true;
      e.preventDefault()
      if (e.dataTransfer.files.length > 0) {
        let file = e.dataTransfer.files[0];
        this.pictureBefore({ file: file });
      }
    },
    pictureBefore(file) {
      let that = this;
      that.isAgain = false;
      that.isSearching = true;
      var reader = new FileReader();
      var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
      var spark = new SparkMD5.ArrayBuffer();
      var reader = new FileReader(); //创建读取文件的方法
      imageConversion.compressAccurately(file.file, 1023).then(cpresFile => {
        reader.readAsArrayBuffer(blobSlice.call(cpresFile));
        reader.onload = async function (e) {
          const image = new Image();
          image.src = URL.createObjectURL(new Blob([e.target.result]));
          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          image.onload = () => {
            canvas.width = image.width
            canvas.height = image.height
            context.drawImage(image, 0, 0)
            const base64 = canvas.toDataURL('image/jpeg')
            localStorage.setItem('tmp_im_b64', base64);
            location.href = '/searchByImageList?t=' + Date.parse(new Date())
          }
        }
      });
    },
    onXsSearch(_base64) {
      this.imgBase64 = localStorage.getItem('tmp_im_b64');
      this.myCropper.destroy();
      this.myCropper.replace(_base64);
      this.handleUrlToSearchByCrop();
    },
    initStickT() {
      this.getMaxHeight();
      setTimeout(() => {
        let lrH = document.getElementsByClassName('layout-right')[0].clientHeight;
        let stkH = document.getElementsByClassName('basic-img-box-wrap')[0].clientHeight;
        // let tgH = document.getElementsByClassName('tj-tag-box')[0].clientHeight;
        // let _top = lrH > stkH ? 115 : -(stkH - document.body.clientHeight + 20 + tgH);
        let _top = lrH > stkH ? 115 : -(stkH - document.body.clientHeight + 20);
        this.stickyTop = _top;
      }, 500)
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    onSImgLoad() {
      let that = this;
      that.myCropper = new Cropper(that.$refs.gimage, {
        viewMode: 1,
        cropBoxResizable: true,
        scalable: false,
        zoomable: false,
        autoCropArea: 1,
        dragMode: "crop",
        toggleDragModeOnDblclick: false,
        cropend: function (e) {
          let data = that.myCropper.getCroppedCanvas({
            imageSmoothingQuality: "high",
          })
            .toDataURL("image/jpeg");
          that.newBase64 = data;
          that.handleUrlToSearchByCrop();
        },
      });
    },
    handleUrlToSearchByCrop() {
      let that = this;
      that.hasMore = true;
      that.imgDataList = [];
      that.scrollLoaded = false;
      that.pageNum = 1;
      that.list = [];
      that.queryList();
    },
    onPaste(e) {
      if(!this.isAgain)return;
      if (e.clipboardData && e.clipboardData.files && e.clipboardData.files.length > 0 && e.clipboardData.files.length == 1) {
        if (e.clipboardData.files[0].type.indexOf('image') < 0) {
          this.$amessage.error('请复制图片后粘贴至此')
          return;
        }
        let _file = e.clipboardData.files[0];
        this.pictureBefore({ file: _file })
      } else {
        this.$amessage.error('请复制图片后粘贴至此')
      }
    },
    onInputFileSearch(e) {
      let imgurl = e.target.value;
      let that = this;
      if (imgurl) {
        new Promise(function (resolve, reject) {
          var ImgObj = new Image();
          ImgObj.src = imgurl;
          ImgObj.onload = function (res) {
            that.handleUrlToSearch(imgurl);
          }
          ImgObj.onerror = function (err) {
            that.$amessage.warn('图片链接无效')
          }
        })
      }
    },
    onOndragLeave(e) {
      this.isDrag = false;
      e.preventDefault();
    },
    onOndragEnter(e) {
      // this.isDrag=true;
      e.preventDefault();
    },
    onOndragover(e) {
      this.isDrag = true;
      e.preventDefault()
    },
    async onDrop(e) {
      // this.isDrag=true;
      e.preventDefault()
      if (e.dataTransfer.files.length > 0) {
        let file = e.dataTransfer.files[0];
        this.pictureBefore({ file: file });
      }
    },
    pictureBefore(file) {
      let that = this;
      that.isAgain = false;
      that.isSearching = true;
      var reader = new FileReader();
      var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
      var spark = new SparkMD5.ArrayBuffer();
      var reader = new FileReader(); //创建读取文件的方法
      imageConversion.compressAccurately(file.file, 1023).then(cpresFile => {
        reader.readAsArrayBuffer(blobSlice.call(cpresFile));
        reader.onload = async function (e) {
          const image = new Image();
          image.src = URL.createObjectURL(new Blob([e.target.result]));
          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          image.onload = () => {
            canvas.width = image.width
            canvas.height = image.height
            context.drawImage(image, 0, 0)
            const base64 = canvas.toDataURL('image/jpeg')
            localStorage.setItem('tmp_im_b64', base64);
            that.isFocus = false;
            location.href = '/searchByImageList?t=' + Date.parse(new Date())
          }
        }
      });

    },
    handleLoadingMore() {
      this.pageNum++;
      this.queryList();
    },
    // 将base64转换为文件
    base64ToFile(str) {
      let arr = str.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], 'ex.png', { type: mime })
    },
        calculateTilt(corners){
            const{x:x1,y:y1}=corners[0];//左上
            const{x:x2,y:y2}=corners[1];// 右上
            // 计算 dy 和 dx
            const dy=y2-y1;
            const dx=x2-x1;
            //计算倾角(弧度->角度)
            const angle =Math.atan2(dy,dx)*(180 /Math.PI);
            // 返回角度
            return angle;
        },
    async queryList() {
      let that = this;
      
      let result ={};
      this.isloading=true;
      let datas=[];
      if(this.pageNum==1){
        // this.list=this.$bhelper.vlist;
      }
      if(this.params.similar){
        result=await api.searchImgs(this.params);
        datas=result.data.images.list;
      }else{
        let formdata = new FormData();
        //   formdata.append("hash", this.hash);
        const _file = this.base64ToFile(this.newBase64 ? this.newBase64 : this.imgBase64);
        formdata.append("image", _file);
        formdata.append("pageNum", this.pageNum);
        // formdata.append("page", this.pageNum);
        formdata.append("pageSize", this.pageSize);
        result = await api.imgToImgUpload(formdata);
        datas=result.list;
      }

      datas.forEach(item => {
          item.show=false;item.showOther=false;
          that.$bhelper.convertImgItem(item,that);
       })
       
      if(datas.length>0)
        this.params.last=datas[datas.length-1].id;

        
      if(this.pageNum==1){
        this.list=datas;
      }else{
        this.list = [...this.list, ...datas];
      }
      if(this.params.similar){
          let totalPage =
            result.total % that.pageSize == 0
              ? result.total / that.pageSize
              : parseInt(result.total / that.pageSize) + 1;
          if ( (result.data && (result.data.length < that.pageSize || that.pageNum >= totalPage))||datas.length<that.params.pageSize ) {
            that.hasMore = false;
          } else {
            that.hasMore = true;
        }
      }else{
        that.hasMore=datas.length!=0;
      }

      this.total = result.total;

      setTimeout(()=>{
          that.isloading = false;
      },300)
      setTimeout(()=>{
          that.scrollLoaded = true;
      },1000)
    }
  }
}
</script>

<style lang="less">
.search-by-image-result-page {
  display: flex;
  align-items: flex-start;
  .layout-left {
    width: 100%;
    margin-left: 36px;
    .top-row {
      display: flex;
      align-items: center;
      // justify-content: space-between;
      // padding-right: 15px;
      position: sticky;
      top: 84px;
      z-index: 114;
      background: #111;
      padding-bottom: 19px;

      .title {
        display: flex;
        font-size: 24px;
        font-weight: 500;

        .num {
          color: #11CCB1;
          margin: 0px 5px;
        }
      }

      .label-filter {
        margin-left: 20px;
        display: flex;
        align-items: center;

        .tit {
          font-size: 14px;
          color: #969696;
        }

        >span {
          display: inline-block;
        }

        .plat-items {
          display: flex;
          align-items: center;

          .pitem {
            width: 30px;
            height: 30px;
            margin-left: 10px;
            display: inline-block;
            cursor: pointer;

            &.windows {
              background: url('../assets/pro/pc_normal_icon.svg') no-repeat;
              background-size: cover;
            }

            &.xbox {
              background: url('../assets/pro/xbox_normal_icon.svg') no-repeat;
              background-size: cover;
            }

            &.switch {
              background: url('../assets/pro/zj_normal_icon.svg') no-repeat;
              background-size: cover;
            }

            &.apple {
              background: url('../assets/pro/mobile_normal_icon.svg') no-repeat;
              background-size: cover;
            }

            &.h-screen {
              background: url('../assets/pro/hb_normal_icon.svg') no-repeat;
              background-size: cover;
              &.active {
                  background: url('../assets/pro/hb_press_icon.svg') no-repeat;
                  background-size: cover;
              }
            }

            &.s-screen {
              background: url('../assets/pro/sp_normal_icon.svg') no-repeat;
              background-size: cover;
              
              &.active {
                  background: url('../assets/pro/sp_press_icon.svg') no-repeat;
                  background-size: cover;
              }
            }
          }
        }
      }
    }
  }

  .layout-right {
    width: 330px;
    min-width: 330px;
    display: flex;
    flex-direction: column;
      position: sticky;
      top: 84px;
    .stick-box {
      position: sticky;
      top: 84px;
    }

    .tit {
      font-size: 24px;
      font-weight: 500;
      margin-bottom: 19px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .mini-tip{
        font-size:14px;
        font-weight:normal;
        color:#969696;
        margin-right:15px;
      }
    }

    .basic-bwrap {
      max-height: 500px;
      overflow-y: auto;
      overflow-x: hidden;
      padding-right: 10px;
    }
      
    .basic-img-box-wrap{
      overflow-y:auto;
      // padding-right:10px;
      overflow-x:hidden;
      background: #11CCB1;
      border-radius: 20px;
      padding-top: 16px;
    }
    .img-box-wra{
      // max-width:calc(100% - 24px);
    }
    .basic-img-box {
      // padding-bottom: 6px;
      position: relative;
      padding-bottom:6px;
      overflow: hidden;
      .op-row {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        position: relative;
        margin-bottom:14px;
        a {
          height: 32px;
          width: 74px;
          line-height: 32px;
          border: 1px solid #fff;
          border-radius: 5px;
          margin-left: 4px;
          text-align: center;
          transition:.1s all linear;
          &:hover{
            background:#fff;
            color:#11CCB1;
          }
        }

        .xs-fav {
          width: 24px;
          height: 24px;
          background: url('../assets/pro/xs_fav.svg') no-repeat;
          border: none;
          position: absolute;
          right: 18px;
          transition: .2s all linear;

          &:hover {
            opacity: .8;
          }
        }
      }

      .img-box {
        // margin:14px 6px 6px 6px;
        // margin: 14px 6px 6px 6px;
        // padding:20px;
        // margin-top:14px 6px 6px 6px;
        margin: 0px 6px;
        max-width:calc(100% - 12px);
        // display: flex;
        // align-items: center;
        // justify-content: center;
        position: relative;

        .img-box-wrap {
          height: calc(100vh - 600px);
          padding-right: 10px;
          overflow-x: hidden;

          .el-scrollbar__wrap {
            overflow-x: hidden;
          }

          .is-horizontal {
            display: none;
          }
        }

        .lt-circle {
          position: absolute;
          width: 26px;
          height: 26px;
          border: 4px solid #fff;
          top: 0px;
          left: 0px;
          border-width: 4px 0 0 4px;
          border-top-left-radius: 16px;
        }

        .rt-circle {
          position: absolute;
          width: 26px;
          height: 26px;
          border: 4px solid #fff;
          top: 0px;
          right: 0px;
          border-width: 4px 4px 0px 0px;
          border-top-right-radius: 16px;
        }

        .lbot-circle {
          position: absolute;
          width: 26px;
          height: 26px;
          border: 4px solid #fff;
          bottom: 0px;
          left: 0px;
          border-width: 0px 0px 4px 4px;
          border-bottom-left-radius: 16px;
        }

        .rbot-circle {
          position: absolute;
          width: 26px;
          height: 26px;
          border: 4px solid #fff;
          bottom: 0px;
          right: 0px;
          border-width: 0px 4px 4px 0px;
          border-bottom-right-radius: 16px;
        }

        img {
          // width:100%;
          // // height:100%;
          // // object-fit: cover;
          // border:1px solid #fff;
          // // margin-top:14px;
          // border-radius:16px;
          // // display:block;
        }
      }
    }

    .tj-tag-box {
      margin-top: 40px;
      background: #181818;
      border-radius: 16px;
      padding: 30px 0px 12px 21px;

      .tit {
        font-size: 14px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;

        &:before {
          content: '';
          width: 49px;
          height: 1px;
          background: #323232;
          position: absolute;
          left: 28%;
        }

        &:after {
          content: '';
          width: 49px;
          height: 1px;
          background: #323232;
          position: absolute;
          right: 28%;
        }
      }

      .tags {
        display: flex;
        flex-wrap: wrap;
        user-select: none;

        a {
          width: 59px;
          height: 34px;
          background: #37363E;
          margin-bottom: 15px;
          color: #fff;
          text-align: center;
          margin-right: 15px;
          line-height: 34px;
          border-radius: 17px;
          font-size: 16px;

          &:nth-child(6n) {
            margin-right: 0px;
          }
        }
      }
    }
  }
}

.bs-layout-fun-mask {
  position: fixed;
  left: 0px;
  right: 0px;
  top: 0px;
  bottom: 0px;
  z-index: 115;
  background:transparent;
}

.bs-layout-rst-fun {
  position:fixed;
  width: 632px;
  height: 434px;
  border-radius: 30px;
  z-index: 115;
  background: #23232A;
  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.5);
  top: 215px;
  left:70px;
  .title {
    // width:170px;
    height: 41px;
    background: url('../assets/pro/smlike_text.svg') no-repeat;
    background-size: 170px 41px;
    background-position: center;
    margin: 0 auto;
    margin-top: 25px;
    position: relative;

    .close-be-simliar {
      position: absolute;
      width: 18px;
      height: 18px;
      position: absolute;
      right: 45px;
      top: 10px;
      background: url('../assets/pro/close-win.svg') no-repeat;
      background-size: cover;
      transition:.1s all linear;
      &:hover{
        transform: rotate(180deg);
      }
    }
  }

  .small-tip {
    color: #969696;
    margin: 29.46px 0px 39.17px 0px;
    font-size: 14px;
    text-align: center;
  }

  .upload-area-wrap {
    width: 539px;
    height: 211px;
    box-shadow: 0px 2px 30px 0px rgba(0, 0, 0, 0.2);
    border-radius: 20px;
    border: 2px dashed rgba(255, 255, 255, 0.14);
    margin: 0 auto;
    padding-top: 38.37px;
    background-image: url('../assets/pro/smlike_transfer.svg');
    background-size: 123px 63px;
    background-repeat: no-repeat;
    background-position: 90% center;
    transition:.1s all linear;
    &:hover{
      border-color:#11CCB1;
    }

    .upload-btn {
      width: 157px;
      height: 61px;
      background: url('../assets/pro/smlike_uploadbtn.svg') no-repeat;
      background-size: cover;
      display: block;
      margin: 0 auto;
      margin-bottom: 26.15px;
      transition:.1s all linear;
      &:hover{
        border-color:#11CCB1;
        background: url('../assets/pro/smlike_transfer_hover.svg') no-repeat;
        background-size: cover;
      }
      .el-upload,
      .el-upload__input {
        width: 100%;
        height: 100%;
      }
    }

    .fun-text {
      font-size: 16px;
      color: #fff;
      font-weight: 500;
      width: 116px;
      display: block;
      text-align: center;
      margin: 0 auto;
    }
  }

  .other-tip {
    margin-top: 39.16px;
    font-size: 12px;
    color: #969696;
    text-align: center;
    margin-bottom: 10.07px;
  }

  .other-sys-imgs {
    display: flex;
    justify-content: center;

    img {
      width: 80px;
      height: 60.21px;
      object-fit: cover;
      margin-right: 10px;
      border-radius: 8px;
      cursor: pointer;
    }
  }
}
</style>